﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using Common.DataTypes;
using LINQAmazonProvider;
using System.Windows.Threading;
using System.Text.RegularExpressions;
using SilverlightApplication1.DataTypes;

namespace SilverlightApplication1
{
    public partial class Page : UserControl
    {       
        private Dispatcher _mainDispatcher;
        private List<Common.DataTypes.Book> lstQueryResult = new List<Book>();
        private Boolean blnAvanced;
        private DTSearchCriteria advanced;
        private int language;
        private string passwordAmazon;
        private Boolean passwordChanged;

        // Atributo sobre el que ejecutaremos las busquedas
        // Amazon Search parameters
        private string searchKeyword; //TODO:: cambiar este atributo para que sea una estructura con toda la info
                                      //de la query a realizar.

        public List<Book> QueryResult
        {
            get
            {
                return lstQueryResult;
            }
            set
            {
                lstQueryResult = value;
            }
        }

        //TODO:: Cambiar el tipo de la Propiedad por la estructura a definir
        public DTSearchCriteria SearchCriteria { get; set; }
        

        public Page()
        {
            InitializeComponent();

            //TODO::Revisar comentario no es correcto y es confuso.
            // Se crea el Searcher y se crea el evento que maneja la finalizacion de la busqueda
            // Create searcher and event to handle search finalization event
            this._mainDispatcher = MainDispatcher.Current;
            //lstQueryResult = new List<Common.DataTypes.Item>();

            //This Boolean allows to manage the Advanced Search section
            blnAvanced = true;

            advanced = new DTSearchCriteria();

            passwordAmazon = "";
            passwordChanged = false;

            language = 1;    //English
            SetLanguage();                        
        }



        /// <summary>
        /// Search information about 'txtQuery' and load it in 'lstResult'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void SearcherFnc()
        {
            //TODO::Eliminar ya que no es necesario ya que no es siempre la misma lista
            //this.lstResult.Items.Clear();
            
            //TODO: Creacion de SearchCriteria
            // Amazon Search parameter
            //advanced.mainKeywords = this.txtQuery.Text;
            
            try
            {
                // Perform Amazon search
                //PerformSearch(keyword);

                // Create thread to perform the amazon search
                Thread worker = new Thread(new ThreadStart(GetLINQResult));

                //TODO:: Cambiar a set de Criteria objeto con toda la info de la busqueda. (No solo Keyword)
                // Set the static parameter Keyword
                SearchCriteria = advanced; //searchKeyword = keyword;
                worker.Start();
            }

            catch (Exception ex)
            {
                // TODO manejar excepcion
            }        
        }


        private void GetLINQResult()
        {
            try
            {
                //TODO::esto se tiene que ir
                List<Book> result = new List<Book>();

                var provider = new AmazonProvider();
                var queryable = new AmazonQuery<Book>(provider);

                if (SearchCriteria.isAdvanced)
                {
                    #region Advanced Search
                    int minPrice = decimal.ToInt32(SearchCriteria.minPrice);
                    int maxPrice = decimal.ToInt32(SearchCriteria.maxPrice);
                    string bookCondition = SearchCriteria.GetCondition();

                    if (SearchCriteria.sortBy != DTSearchCriteria.NOTHING)
                    {
                        #region Sort criteria ON
                        if (SearchCriteria.category != DTSearchCriteria.NOTHING)
                        {
                            #region Sort criteria ON, Category criteria ON
                            if (SearchCriteria.maxPrice != 0)
                            {
                                #region Sort criteria ON, Category criteria ON, Maximum Price Criteria ON
                                if (SearchCriteria.sortBy == DTSearchCriteria.LST_PRICE_ASC)
                                {
                                    #region Sort criteria ON - LIST PRICE ASC, Category criteria ON, Maximum Price Criteria ON
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.LST_PRICE_DSC)
                                {
                                    #region Sort criteria ON - LIST PRICE DESC, Category criteria ON, Maximum Price Criteria ON
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.TITLE)
                                {
                                    #region Sort criteria ON - TITLE, Category criteria ON, Maximum Price Criteria ON
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.PUB_DATE)
                                {
                                    #region Sort criteria ON - PUB DATE, Category criteria OFF, Maximum Price Criteria ON
                                    #endregion
                                }
                                #endregion
                            }
                            else
                            {
                                #region Sort criteria ON, Category criteria ON, Maximum Price Criteria OFF
                                if (SearchCriteria.sortBy == DTSearchCriteria.LST_PRICE_ASC)
                                {
                                    #region Sort criteria ON - LIST PRICE ASC, Category criteria ON, Maximum Price Criteria ON
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.LST_PRICE_DSC)
                                {
                                    #region Sort criteria ON - LIST PRICE DESC, Category criteria ON, Maximum Price Criteria ON
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.TITLE)
                                {
                                    #region Sort criteria ON - TITLE, Category criteria ON, Maximum Price Criteria ON
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.PUB_DATE)
                                {
                                    #region Sort criteria ON - PUB DATE, Category criteria OFF, Maximum Price Criteria ON
                                    #endregion
                                }
                                #endregion
                            }
                            #endregion
                        }
                        else
                        {
                            #region Sort criteria ON, Category criteria OFF
                            if (SearchCriteria.maxPrice != 0)
                            {
                                #region Sort criteria ON, Category criteria OFF, Maximum Price Criteria ON
                                if (SearchCriteria.sortBy == DTSearchCriteria.LST_PRICE_ASC)
                                {
                                    #region Sort criteria ON - LIST PRICE ASC, Category criteria OFF, Maximum Price Criteria ON
                                    var query =
                                        from book in queryable
                                        where
                                          book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                          book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                          book.ListPrice.Amount >= minPrice && book.ListPrice.Amount <= maxPrice &&
                                          book.Keywords == SearchCriteria.keywords
                                        orderby book.ListPrice
                                        select book;

                                    result = query.ToList<Book>();
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.LST_PRICE_DSC)
                                {
                                    #region Sort criteria ON - LIST PRICE DESC, Category criteria OFF, Maximum Price Criteria ON
                                    var query =
                                            from book in queryable
                                            where
                                              book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                              book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                              book.ListPrice.Amount >= minPrice && book.ListPrice.Amount <= maxPrice &&
                                              book.Keywords == SearchCriteria.keywords
                                            orderby book.ListPrice descending
                                            select book;

                                    result = query.ToList<Book>();
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.TITLE)
                                {
                                    #region Sort criteria ON - TITLE, Category criteria OFF, Maximum Price Criteria ON
                                    var query =
                                            from book in queryable
                                            where
                                              book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                              book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                              book.ListPrice.Amount >= minPrice && book.ListPrice.Amount <= maxPrice &&
                                              book.Keywords == SearchCriteria.keywords
                                            orderby book.Title
                                            select book;

                                    result = query.ToList<Book>();
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.PUB_DATE)
                                {
                                    #region Sort criteria ON - PUB DATE, Category criteria OFF, Maximum Price Criteria ON
                                    var query =
                                                from book in queryable
                                                where
                                                  book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                                  book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                                  book.ListPrice.Amount >= minPrice && book.ListPrice.Amount <= maxPrice &&
                                                  book.Keywords == SearchCriteria.keywords
                                                orderby book.PublicationDate
                                                select book;

                                    result = query.ToList<Book>();
                                    #endregion
                                }
                                #endregion
                            }
                            else
                            {
                                #region Sort criteria ON, Category criteria OFF, Maximum Price Criteria OFF
                                if (SearchCriteria.sortBy == DTSearchCriteria.LST_PRICE_ASC)
                                {
                                    #region Sort criteria ON - LIST PRICE ASC, Category criteria OFF, Maximum Price Criteria OFF
                                    var query =
                                        from book in queryable
                                        where
                                          book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                          book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                          book.ListPrice.Amount >= minPrice && book.Keywords == SearchCriteria.keywords

                                        orderby book.ListPrice
                                        select book;

                                    result = query.ToList<Book>();
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.LST_PRICE_DSC)
                                {
                                    #region Sort criteria ON - LIST PRICE DESC, Category criteria OFF, Maximum Price Criteria OFF
                                    var query =
                                        from book in queryable
                                        where
                                          book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                          book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                          book.ListPrice.Amount >= minPrice && book.Keywords == SearchCriteria.keywords

                                        orderby book.ListPrice descending
                                        select book;

                                    result = query.ToList<Book>();
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.TITLE)
                                {
                                    #region Sort criteria ON - TITLE, Category criteria OFF, Maximum Price Criteria OFF
                                    var query =
                                                from book in queryable
                                                where
                                                  book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                                  book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                                  book.ListPrice.Amount >= minPrice && book.Keywords == SearchCriteria.keywords

                                                orderby book.Title
                                                select book;

                                    result = query.ToList<Book>();
                                    #endregion
                                }
                                else if (SearchCriteria.sortBy == DTSearchCriteria.PUB_DATE)
                                {
                                    #region Sort criteria ON - PUB DATE, Category criteria OFF, Maximum Price Criteria OFF
                                    var query =
                                        from book in queryable
                                        where
                                          book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                          book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                          book.ListPrice.Amount >= minPrice && book.Keywords == SearchCriteria.keywords
                                         
                                        orderby book.PublicationDate
                                        select book;

                                    result = query.ToList<Book>();
                                    #endregion
                                }
                                #endregion
                            }
                            #endregion
                        }
                        #endregion
                    }
                    else
                    {
                        #region Sort criteria OFF
                        if (SearchCriteria.category != DTSearchCriteria.NOTHING)
                        {
                            #region Sort criteria OFF, Category criteria ON
                            if (SearchCriteria.maxPrice != 0)
                            {
                                #region Sort criteria OFF, Category criteria ON, Maximum Price Criteria ON
                                #endregion
                            }
                            else
                            {
                                #region Sort criteria OFF, Category criteria ON, Maximum Price Criteria OFF
                                #endregion
                            }
                            #endregion
                        }
                        else
                        {
                            #region Sort criteria OFF, Category criteria OFF
                            if (SearchCriteria.maxPrice != 0)
                            {
                                #region Sort criteria OFF, Category criteria OFF, Maximum Price Criteria ON
                                var query =
                                        from book in queryable
                                        where
                                          book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                          book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                          book.ListPrice.Amount >= minPrice && book.ListPrice.Amount <= maxPrice &&
                                          book.Keywords == SearchCriteria.keywords
                                        select book;

                                result = query.ToList<Book>();
                                #endregion
                            }
                            else
                            {
                                #region Sort criteria OFF, Category criteria OFF, Maximum Price Criteria OFF
                                var query =
                                    from book in queryable
                                    where
                                      book.Author == SearchCriteria.author && book.Publisher == SearchCriteria.publisher &&
                                      book.Title == SearchCriteria.title && book.Condition == bookCondition &&
                                      book.ListPrice.Amount >= minPrice && book.Keywords == SearchCriteria.keywords
                                    select book;

                                result = query.ToList<Book>();
                                #endregion
                            }
                            #endregion
                        }
                        #endregion
                    }
                    #endregion
                }
                else
                {
                    #region Normal Search
                    var query =
                    from book in queryable
                    where
                      book.Keywords == SearchCriteria.mainKeywords
                    select book;

                    result = query.ToList<Book>();
                    #endregion
                }
                
                //Invoque the event on the UiThread
                _mainDispatcher.BeginInvoke(delegate()
                {
                    //OnSearchCompleted(new SearchCompletedEventArgs(result));
                    //TODO::Arreglar problema de tipos que retorna y aarreglar
                    SearchCompleted(result);
                });
            }
            catch (Exception e)
            {
                //TODO:: ver de hacer manejo de la excepcion o sacar
                throw e;
            }
        }

        private void SearchCompleted(IEnumerable<Book> query)
        {
            hlnkAdvSearch.Foreground = new SolidColorBrush(Colors.Black);
            lstResult.ItemsSource = query;
            lstResult.Visibility = Visibility.Visible;
        }

        void Search_Click(object sender, EventArgs args)
        {
            advanced.isAdvanced = false;
            advanced.mainKeywords = this.txtQuery.Text;

            SearcherFnc();
        }

        #region Metodos viejos al finalizar la busqueda
        //private void OnSearchCompleted(SearchCompletedEventArgs e)
        //{
        //    searcher_SearchCompleted(this, e);
        //}
        
        //// Function to handle search complete event
        //void searcher_SearchCompleted(object sender, SearchCompletedEventArgs e)
        //{
        //    /*this.textprueba.Text = "DESPUES DE TERMINAR: ";

        //    Common.DataTypes.Book book;
        //    foreach (Common.DataTypes.Item i in e.Result)
        //    {
        //        book = (Common.DataTypes.Book)i;
        //        textprueba.Text += book.Author + " ";
        //    }*/
            
        //    Common.DataTypes.Book b;

        //    lstQueryResult.Clear();
        //    foreach (Common.DataTypes.Item i in e.Result)
        //    {
        //        //Add the Item to our local variable
        //        lstQueryResult.Add(i);
        //    }

        //    //In future this will be relative to the page
        //    for (int Index = 0; Index<5; Index++)
        //    {
        //        b = (Common.DataTypes.Book)lstQueryResult[Index];

        //        ListBoxItem item = new ListBoxItem();
        //        ListItemControl lstItemCtrl = new ListItemControl();
        //        lstItemCtrl.Tag = Index;
        //        lstItemCtrl.imgData.MouseLeftButtonDown += new MouseButtonEventHandler(ShowItemInformation);
        //        lstItemCtrl.imgData.Source = new BitmapImage(new Uri(b.MediumImage, UriKind.Absolute));
        //        lstItemCtrl.txtInfo1.Text = b.Author;
        //        lstItemCtrl.txtInfo2.Text = b.Title;
        //        lstItemCtrl.txtInfo3.Text = b.Publisher;
        //        lstItemCtrl.txtInfo4.Text = "Price: " + b.ListPrice.CurrencyCode + " " + b.ListPrice.FormattedPrice;
        //        item.Content = lstItemCtrl;
        //        lstResult.Items.Add(item);
        //    }

        //    lstResult.Visibility = Visibility.Visible;
        //}
        #endregion

        #region UI Methods
        void txtQueryKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                advanced.mainKeywords = this.txtQuery.Text;
                advanced.isAdvanced = false;
                SearcherFnc();
            }
        }

        void ShowItemInformation(object sender, MouseButtonEventArgs e)
        {
            // This code sets the VerticalAlignment of the 'grdLstItemInfo' control
            Point p = e.GetPosition(lstResult);
            if (p.Y < (lstResult.ActualHeight / 3))
                grdLstItemInfo.VerticalAlignment = VerticalAlignment.Top;
            else
                if (p.Y > (2 * (lstResult.ActualHeight / 3)))
                    grdLstItemInfo.VerticalAlignment = VerticalAlignment.Bottom;
                else
                    grdLstItemInfo.VerticalAlignment = VerticalAlignment.Center;
            /*
             * The event SelectionChanged is executed before the event ShowItemInformation,
             * so at this moment we don't know which item contain the selected photo,
             * and for this reason here we simulate the event SelectionChanged.
             */
            lstResultSelectionChanged(sender, null);  
            /*
            //ListItemControl Item = ((ListItemControl)(((StackPanel)((Image)sender).Parent).Parent));
            ContentPresenter Item = ((ContentPresenter)(((StackPanel)((Image)sender).Parent).Parent));

            //Common.DataTypes.Book b = ((Common.DataTypes.Book)lstQueryResult[((int)Item.Tag)]);
            Common.DataTypes.Book b = ((Common.DataTypes.Book)lstQueryResult[(lstResult.Items.IndexOf(Item))]);

            imgItemInformation.Source = new BitmapImage(new Uri(b.LargeImage, UriKind.Absolute));
            txtItemInfo1.Text = b.Author;            
            txtItemInfo2.Text = b.Publisher;
            txtItemInfo3.Text = b.Title;
            
            infoItemVisible.Begin();
             */
        }

        void lstResultSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            List<Item> lst = new List<Item>();
            lst.Add((Item)lstResult.SelectedItem);
            icMoreInfo.ItemsSource = (IEnumerable<Item>)lst;
            infoItemVisible.Begin();
        }

        void CloseItemInformation(object sender, EventArgs args)
        {
            infoItemNotVisible.Begin();
            //icMoreInfo.Items.Clear();
        }
        
        void btnBooksToBigger(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderBigger.Stop();

            Storyboard.SetTargetName(renderBigger, "rdrBooks");
            rdrBooks.CenterX = 30;
            rdrBooks.CenterY = 30;
            renderBigger.Begin();
        }

        void btnBooksToLower(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderLower.Stop();

            Storyboard.SetTargetName(renderLower, "rdrBooks");
            renderLower.Begin();
        }

        void btnAbout1ToBigger(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderBigger.Stop();

            Storyboard.SetTargetName(renderBigger, "rdrAbout1");
            rdrAbout1.CenterX = 30;
            rdrAbout1.CenterY = 30;
            renderBigger.Begin();
        }

        void btnAbout1ToLower(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderLower.Stop();

            Storyboard.SetTargetName(renderLower, "rdrAbout1");
            renderLower.Begin();
        }

        void btnAbout2ToBigger(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderBigger.Stop();

            Storyboard.SetTargetName(renderBigger, "rdrAbout2");
            rdrAbout2.CenterX = 30;
            rdrAbout2.CenterY = 30;
            renderBigger.Begin();
        }

        void btnAbout2ToLower(object sender, EventArgs args)
        {
            // Case the storyboard is still executing on other button, it's stoped
            renderLower.Stop();

            Storyboard.SetTargetName(renderLower, "rdrAbout2");
            renderLower.Begin();
        }

        void Advanced(object sender, EventArgs args)
        {
            if (sender.GetType().Equals(hlnkAdvSearch.GetType()))
            {
                loadOptions();
                grdAdvSearch.Visibility = Visibility.Visible;
                //toVisible.Begin();
                /*
                if (blnAvanced)
                {
                    loadOptions();
                    toVisible.Begin();
                }
                else
                {
                    toNotVisible.Begin();
                    saveOptions();
                }
                */
            }
            else
            {
                if (ValidarDatos())
                {
                    grdAdvSearch.Visibility = Visibility.Collapsed;
                    if (((Button)sender).Name == btnConfirm.Name)
                    {
                        saveOptions();
                        advanced.isAdvanced = true;
                        SearcherFnc();
                    }
                }
                else
                {
                    //show msgbox
                }
            }
            blnAvanced = !blnAvanced;
        }
        
        void btnConfirmToLight(object sender, EventArgs args)
        {
            imgDarkGreen.Visibility = Visibility.Collapsed;
            imgLightGreen.Visibility = Visibility.Visible;
        }

        void btnConfirmToDark(object sender, EventArgs args)
        {
            imgDarkGreen.Visibility = Visibility.Visible;
            imgLightGreen.Visibility = Visibility.Collapsed;
        }

        void btnCancelToLight(object sender, EventArgs args)
        {
            imgDarkRed.Visibility = Visibility.Collapsed;
            imgLightRed.Visibility = Visibility.Visible;
        }

        void btnCancelToDark(object sender, EventArgs args)
        {
            imgDarkRed.Visibility = Visibility.Visible;
            imgLightRed.Visibility = Visibility.Collapsed;
        }
        #endregion    

        #region AdvancedSearch
        
        public void loadOptions()
        {
            //Sort by
            rbtPrice.IsChecked = (advanced.sortBy == DTSearchCriteria.LST_PRICE_ASC) ||
                                 (advanced.sortBy == DTSearchCriteria.LST_PRICE_DSC);
            rbtAsc.IsChecked = (advanced.sortBy == DTSearchCriteria.LST_PRICE_ASC);
            rbtDesc.IsChecked = (advanced.sortBy == DTSearchCriteria.LST_PRICE_DSC);
            rbtPublDate.IsChecked = (advanced.sortBy == DTSearchCriteria.PUB_DATE);
            rbtTitle.IsChecked = (advanced.sortBy == DTSearchCriteria.TITLE);
            
            //Filtered by
            //Author
            txtAuthor.Text = advanced.author;
            //Publisher
            txtPublisher.Text = advanced.publisher;
            //Title
            txtTitle.Text = advanced.title;
            //Category
            //TODO
            //Condition
            chkUsed.IsChecked = (advanced.condition.Substring(DTSearchCriteria.COND_USED, 1) == "1");
            chkCollectible.IsChecked = (advanced.condition.Substring(DTSearchCriteria.COND_COLLECTIBLE, 1) == "1");
            chkRefurbished.IsChecked = (advanced.condition.Substring(DTSearchCriteria.COND_REFURBISHED, 1) == "1");
            //KeyWord
            txtKeyword.Text = advanced.keywords;
            //Max Price
            txtMaxPrice.Text = advanced.maxPrice > 0 ? advanced.maxPrice.ToString(): "";
            //Min Price
            txtMinPrice.Text = advanced.minPrice > 0 ? advanced.minPrice.ToString() : "";
        }
        
        public void saveOptions()
        {
            //Sort by
            if (rbtPrice.IsChecked.Value)
            {
                advanced.sortBy = rbtAsc.IsChecked.Value ? DTSearchCriteria.LST_PRICE_ASC : DTSearchCriteria.LST_PRICE_DSC;
            }
            else if (rbtPublDate.IsChecked.Value)
            {
                advanced.sortBy = DTSearchCriteria.PUB_DATE;
            }
            else if (rbtTitle.IsChecked.Value)
            {
                advanced.sortBy = DTSearchCriteria.TITLE;
            }
            else
            {
                advanced.sortBy = DTSearchCriteria.NOTHING;
            }

            
            //Filtered by

            //Author
            advanced.author = txtAuthor.Text.Trim();
            //Publisher
            advanced.publisher=txtPublisher.Text.Trim();
            //Title
            advanced.title = txtTitle.Text.Trim();
            //Category
            //TODO
            //Condition
            string Aux;
            Aux = chkUsed.IsChecked.Value ? "1" : "0";
            Aux += chkCollectible.IsChecked.Value ? "1" : "0";
            Aux += chkRefurbished.IsChecked.Value ? "1" : "0";
            advanced.condition = Aux;

            //KeyWord
            advanced.keywords = txtKeyword.Text.Trim();            
            //Max Price
            advanced.maxPrice= (txtMaxPrice.Text.Trim()!= "") ? decimal.Parse(txtMaxPrice.Text.Trim()):0 ;
            //Min Price
            advanced.minPrice = (txtMinPrice.Text.Trim() != "") ? decimal.Parse(txtMinPrice.Text.Trim()): 0;
            
        }

        public bool ValidarDatos()
        {
            Boolean validar = false;
            
            Regex reg = new Regex(@"^[0-9]*$");

            //Max Price is numeric?
            validar = reg.IsMatch(txtMaxPrice.Text.Trim()) || (txtMaxPrice.Text.Trim()=="");
            //Min Price is numeric?
            validar = validar & (reg.IsMatch(txtMinPrice.Text.Trim()) || (txtMinPrice.Text.Trim()==""));

            return validar;
        }

        #endregion

        #region Language

        void ChangeLanguage(object sender, EventArgs args)
        {
            language = (language == 1) ? 2 : 1;
            SetLanguage();
        }

        private void SetLanguage()
        {
            TextLanguage textL = new TextLanguage();
            
            //Amazon Key
            AmazonKey.Text = textL.GetText(TextLanguage.fields.key_title, language);
            //Sign In
            hlkSignIn.Content = textL.GetText(TextLanguage.fields.key_signin, language);
            //Search
            btnSearch.Content = textL.GetText(TextLanguage.fields.search, language);
            //Advanced Search
            hlnkAdvSearch.Content = textL.GetText(TextLanguage.fields.adv_lnk, language);
            lblAdvanced.Text = textL.GetText(TextLanguage.fields.adv_title, language);
            //Sort
            lblSort.Text = textL.GetText(TextLanguage.fields.adv_sortby, language);
            rbtPrice.Content = textL.GetText(TextLanguage.fields.adv_sort_price, language);
            rbtAsc.Content = textL.GetText(TextLanguage.fields.adv_sort_price_asc, language);
            rbtDesc.Content = textL.GetText(TextLanguage.fields.adv_sort_price_dsc, language);
            rbtPublDate.Content = textL.GetText(TextLanguage.fields.adv_sort_pubdate, language);
            rbtTitle.Content = textL.GetText(TextLanguage.fields.adv_sort_title, language);
            //Filtered
            lblFiltered.Text = textL.GetText(TextLanguage.fields.adv_filteredby, language);
            lblAuthor.Text = textL.GetText(TextLanguage.fields.adv_filt_author, language);
            lblPublisher.Text = textL.GetText(TextLanguage.fields.adv_filt_publisher, language);
            lblTitle.Text = textL.GetText(TextLanguage.fields.adv_filt_title, language);
            lblCategory.Text = textL.GetText(TextLanguage.fields.adv_filt_category, language);
            lblCondition.Text = textL.GetText(TextLanguage.fields.adv_filt_condition, language);
            chkUsed.Content = textL.GetText(TextLanguage.fields.adv_filt_cond_used, language);
            chkCollectible.Content = textL.GetText(TextLanguage.fields.adv_filt_cond_coll, language);
            chkRefurbished.Content = textL.GetText(TextLanguage.fields.adv_filt_cond_refu, language);
            lblKeyword.Text = textL.GetText(TextLanguage.fields.adv_filt_keyword, language);
            lblMaxPrice.Text = textL.GetText(TextLanguage.fields.adv_filt_maxprice, language);
            lblMinPrice.Text = textL.GetText(TextLanguage.fields.adv_filt_minprice, language);

            imgEEUU.Visibility = (language == 2) ? Visibility.Visible : Visibility.Collapsed;
            imgES.Visibility = (language == 1) ? Visibility.Visible : Visibility.Collapsed;
        }

        #endregion

        #region Password

        void txtKey_KeyDown(object sender, KeyEventArgs args)
        {
            passwordChanged = true;
        }

        void txtKey_TextChanged(object sender, TextChangedEventArgs args)
        {
            if (passwordChanged)
            {
                int Index = txtKey.SelectionStart;

                int Rest = txtKey.Text.Length - passwordAmazon.Length;

                if (Rest > 0)
                {
                    passwordAmazon = passwordAmazon.Insert(txtKey.SelectionStart - Rest, txtKey.Text.Substring(txtKey.SelectionStart - Rest, Rest));
                }
                else if (Rest == 0)
                {
                    passwordAmazon = passwordAmazon.Substring(0, txtKey.SelectionStart - 1)
                                  + txtKey.Text.Substring(txtKey.SelectionStart - 1, 1)
                                  + passwordAmazon.Substring(txtKey.SelectionStart, passwordAmazon.Length - txtKey.SelectionStart);

                }
                else
                {
                    Rest = Rest * -1;
                    passwordAmazon = passwordAmazon.Remove(txtKey.SelectionStart, Rest);
                }

                txtKey.Text = new string('*', txtKey.Text.Length);
                txtKey.SelectionStart = Index;
                passwordChanged = false;

            }
        }

        #endregion
    }

}
